package cron

import (
	"bigdevops/src/models"
	"context"
	"fmt"
	"go.uber.org/zap"
)

// renew map方式

func (ac *AlertCache) RenewMapRule(ctx context.Context) {

	// 先从数据库中查询出所有
	rules, err := models.GetMonitorAlertRuleAll()
	if err != nil {
		ac.Sc.Logger.Error("[缓存刷新模块]扫描数据库中的Rules失败",
			zap.Error(err),
		)
		return
	}
	if len(rules) == 0 {
		return
	}

	tmpM := map[string]*models.MonitorAlertRule{}
	for _, Rule := range rules {
		Rule := Rule
		tmpM[fmt.Sprintf("%d", Rule.ID)] = Rule
	}

	// 模拟 数据量很大，刷新缓存很慢
	//time.Sleep(30 * time.Second)

	ac.RuleLock.Lock()
	lastNum := len(ac.SendGroupMap)
	ac.RuleMap = tmpM
	thiNum := len(ac.SendGroupMap)

	ac.RuleLock.Unlock()
	ac.Sc.Logger.Info("RenewMapRule 刷新缓存结果....",
		zap.Any("上一次数量", lastNum),
		zap.Any("这一次数量", thiNum),
	)

}

func (ac *AlertCache) GetRuleById(id string) *models.MonitorAlertRule {

	ac.RuleLock.RLock()
	defer ac.RuleLock.RUnlock()
	return ac.RuleMap[id]
}
